package com.backend.demo1.services;

import com.backend.demo1.config.ApiException;
import com.backend.demo1.mapper.DepartmentMapper;
import com.backend.demo1.mapper.UserMapper;
import com.backend.demo1.models.Department;
import com.backend.demo1.models.User;
import com.backend.demo1.utils.PasswordUtil;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DepartmentMapper departmentMapper;


    @Autowired
    private PasswordUtil passwordUtil;


    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    public void updateUser(Long id, User user) {
        User existingUser = userMapper.selectUserById(id);
        if (existingUser == null) {
            throw new ApiException(404, "用户不存在");
        }

        // 更新用户信息
        existingUser.setUsername(user.getUsername());
        existingUser.setPassword(passwordUtil.hashPassword(user.getPassword()));
        existingUser.setRole(user.getRole());

        userMapper.updateUser(existingUser);
    }

    public void deleteUser(Long id) {
        User existingUser = userMapper.selectUserById(id);
        if (existingUser == null) {
            throw new ApiException(404, "用户不存在");
        }
        userMapper.deleteUser(id);
    }

    public User getUserWithDepartmentById(Long id) {
        User user = userMapper.selectUserById(id);// 获取用户基本信息
        if (user != null && user.getDepartmentId() != null) {
            Department department = departmentMapper.findById(user.getDepartmentId()); // 单独查部门
            user.setDepartment(department); // 设置关联的部门
        }
        return user;
    }


}